package com.akbar.utils;


import com.akbar.properties.JwtProperties;
import io.jsonwebtoken.*;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

@Slf4j
@Component
public class JwtUtil {

    @Autowired
    private JwtProperties jwtProperties;

    private SecretKey secretKey;

    // @PostConstruct 是Java标准注解（JSR-250），用于标记在依赖注入完成后需要执行的初始化方法。
    @PostConstruct
    public void init() {
        // 应用启动时生成一次密钥
        this.secretKey = Jwts.SIG.HS256.key().build();
    }


    // 生成JWT
    public String generateToken(Map<String, Object> claims) {

        Date currentDate = new Date();
        Date expireDate = new Date(currentDate.getTime() + jwtProperties.getExpiration());

        return Jwts.builder()
                .claims(claims)
                .issuedAt(new Date())    // token签发时间
                .expiration(expireDate)  // 毫秒（milliseconds）为单位
                .signWith(secretKey, Jwts.SIG.HS256)
                .compact();
    }

    // 从 Jwt token 获取用户名
    public Claims getPayload(String token){
        return Jwts.parser()
                .verifyWith(secretKey)
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }


    // 验证 Jwt token
    public boolean validateToken(String token){
        try{
            Jwts.parser()
                    .verifyWith(secretKey)
                    .build()
                    .parseSignedClaims(token);
            return true;
        } catch (MalformedJwtException e) {
            throw new JwtException("无效的 JWT token");
        } catch (ExpiredJwtException e) {
            throw new JwtException("JWT 已过期");
        } catch (UnsupportedJwtException e) {
            throw new JwtException("不支持的 JWT token");
        } catch (IllegalArgumentException e) {
            throw new JwtException("JWT 内容为空");
        }
    }
}
